package com.jade.web.controller.file;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jade.common.config.Global;
import com.jade.modle.FileMeta;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;


@Controller
@RequestMapping("/fileUpload")
public class FileController {
 
    LinkedList<FileMeta> files = new LinkedList<FileMeta>();
    // 图片预览路径
    List<String> previewSrcList = new ArrayList<String>();
    // 返回值
    Map<String, Object> previewData = new HashMap<String, Object>();
    
    FileMeta fileMeta = null;
    @Value("${file_uploadPath}")
    private String uploadPath;
    
    /**
     * 上传视图
     * @return
     */
    @GetMapping("/uploadView")
    public String uploadView()
    {
        return "ui/layout/upFile";
    }
    
    //TODO 以后缺拦截，做权限的控制
    
    
    @RequestMapping(value="/upload")
    @ResponseBody
    public List<FileMeta> upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    
         Iterator<String> itr =  request.getFileNames();
         MultipartFile mpf = null;
         //TODO 以后如果多项目用，应该是要带项目名的，这样可以多项目文件分开。但是上传要前端带项目名感觉不合适，待定
         
         //TODO 去掉这部分，改成新的文件生成规则，配置文件取目录，然后生成除重的文件夹和文件。
         //TODO 加插入文件表
         //TODO 
         String path= getFolder();
         //String uplaodPath = Global.getConfig("jade.profile")+File.separatorChar + "template" + File.separatorChar + "upload";
         System.out.println("Upload:"+path);
         File FilePath = new File(path);
         if (!FilePath.exists()) {
     		FilePath.mkdirs();
     	}
         // 定义当前时间，作为文件名称
         long time = System.currentTimeMillis() ;
         //2. get each file
         while(itr.hasNext()){
             //2.1 get next MultipartFile
             mpf = request.getFile(itr.next()); 
             System.out.println(mpf.getOriginalFilename() +" uploaded! "+files.size());
             System.out.println(mpf.getOriginalFilename() +" uploaded2! "+files.size());
             //2.2 if files > 10 remove the first from the list
             if(files.size() >= 10)
                 files.pop();
             //2.3 create new fileMeta
             fileMeta = new FileMeta();
             fileMeta.setFileName(mpf.getOriginalFilename());
             fileMeta.setFileSize(mpf.getSize()/1024+" Kb");
             fileMeta.setFileType(mpf.getContentType());
             try {
                 fileMeta.setBytes(mpf.getBytes());
//                  FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream("D:/temp/files/"+mpf.getOriginalFilename()));
               // String path = uplaodPath + File.separatorChar + time + "_" + mpf.getOriginalFilename();
                
                FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(path));
//                
            } catch (IOException e) {
                e.printStackTrace();
            }
             files.add(fileMeta);
         }
        return files;
    }
    
    private String getFolder() {
    	Calendar ca=Calendar.getInstance();
    	int year = ca.get(1);
    	int month = ca.get(2);
    	int date = ca.get(5);
		return year+month+date+"";
	}

	@RequestMapping(value="/uploadAndPreview")
    @ResponseBody
    public String uploadAndPreview(MultipartHttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html");
    	Iterator<String> itr =  request.getFileNames();
        MultipartFile mpf = null;

        // 返回值
        Map<String, Object> data = new HashMap<String, Object>();

        data.put("sta", "true");

        // 目录文件夹（没有做文件是否存在等判断，需写方法处理）
        String dirPath = File.separatorChar + "template" + File.separatorChar + "upload";
        String uplaodPath = request.getSession().getServletContext().getRealPath(dirPath);
        // 定义当前时间，作为文件名称（目前没有做同名文件分开存储处理）
        long time = System.currentTimeMillis() ;
        //2. get each file

        files.clear();
        while(itr.hasNext()){
//
            mpf = request.getFile(itr.next()); 
            System.out.println(mpf.getOriginalFilename() +" uploaded! "+files.size());
            
            /*String path = "D:/temp/files/" + File.separatorChar + time + "_" + mpf.getOriginalFilename();*/
            
            String path = uplaodPath + File.separatorChar + mpf.getOriginalFilename();

            //2.2 if files > 10 remove the first from the list
            if(files.size() >= 10)
                files.pop();

            //2.3 create new fileMeta
            fileMeta = new FileMeta();
            fileMeta.setFileName(mpf.getOriginalFilename());
//            fileMeta.setFileSize(mpf.getSize()/1024+" Kb");
//            fileMeta.setFileType(mpf.getContentType());
//
            try {
//                fileMeta.setBytes(mpf.getBytes());

                //超过500MB之后可能存在内存溢出的问题
                FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(path));

                // 设置图片预览地址
                fileMeta.setPreviewSrc(dirPath+File.separatorChar + mpf.getOriginalFilename());
           } catch (IOException e) {
               e.printStackTrace();
               // 设置图片上传失败
                data.put("sta", "false");
           }
            files.add(fileMeta);
            /*// 设置图片预览路径
            previewSrcList.add(path);*/
        }
        
       /* previewData.put("previewData", previewSrcList);*/
        data.put("files", files);
        //为了支持IE8，9两个版本，不使用的话，IE8,9会提示下载文件

        try{
            JSONObject itemJSONObj = JSONObject.parseObject(JSON.toJSONString(data));
            return itemJSONObj.toString();
        }catch (Exception e){
        	return "";
        }
        
    }
   
    /***************************************************
     * URL: /rest/controller/upload     , method = RequestMethod.POST
     * upload(): receives files
     * @param request : MultipartHttpServletRequest auto passed
     * @param response : HttpServletResponse auto passed
     * @return LinkedList<FileMeta> as json format   LinkedList<FileMeta>
     ****************************************************/
    @RequestMapping(value="/newuploadAndPreview")
    @ResponseBody
    public Map<String, Object> newuploadAndPreview(MultipartHttpServletRequest request, HttpServletResponse response) {
    	Iterator<String> itr =  request.getFileNames();
        MultipartFile mpf = null;
        
        LinkedList<FileMeta> files = new LinkedList<FileMeta>();
        // 返回值
        Map<String, Object> previewData = new HashMap<String, Object>();
        
        previewData.put("sta", "true");

        // 目录文件夹
        String dirPath = File.separatorChar + "template" + File.separatorChar + "upload";
        String uplaodPath = request.getSession().getServletContext().getRealPath(dirPath);
        // 定义当前时间，作为文件名称
        long time = System.currentTimeMillis() ;
        //2. get each file
        while(itr.hasNext()){

            //2.1 get next MultipartFile
            mpf = request.getFile(itr.next()); 
            System.out.println(mpf.getOriginalFilename() +" uploaded! "+files.size());
            
            /*String path = "D:/temp/files/" + File.separatorChar + time + "_" + mpf.getOriginalFilename();*/
            
            String path = uplaodPath + File.separatorChar + mpf.getOriginalFilename();

            //2.3 create new fileMeta
            FileMeta fileMeta = new FileMeta();
            fileMeta.setFileName(mpf.getOriginalFilename());
            fileMeta.setFileSize(mpf.getSize()/1024+" Kb");
            fileMeta.setFileType(mpf.getContentType());

            try {
                fileMeta.setBytes(mpf.getBytes());
                
                FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(path));
                
                // 设置图片预览地址
                fileMeta.setPreviewSrc(dirPath+File.separatorChar + mpf.getOriginalFilename());
           } catch (IOException e) {
               e.printStackTrace();
               // 设置图片上传失败
               previewData.put("sta", "false");
           }
            files.add(fileMeta);
            /*// 设置图片预览路径
            previewSrcList.add(path);*/
        }
        
       /* previewData.put("previewData", previewSrcList);*/
        previewData.put("files", files);
        
        
       return previewData;
    }
    
    /***************************************************
     * URL: /rest/controller/upload     , method = RequestMethod.POST
     * upload(): receives files
     * @param request : MultipartHttpServletRequest auto passed
     * @param response : HttpServletResponse auto passed
     * @return LinkedList<FileMeta> as json format   LinkedList<FileMeta>
     ****************************************************/
    @RequestMapping(value="/XHRuploadAndPreview")
    @ResponseBody
    public Map<String, Object> XHRuploadAndPreview(@RequestParam(required=false) MultipartHttpServletRequest request, @RequestParam(value="files",required=false) CommonsMultipartFile[] file, @RequestParam(required=false) HttpServletResponse response) {
    	Iterator<String> itr =  request.getFileNames();
    	
    	System.out.print("========="+file.length);
    	
        MultipartFile mpf = null;
        
        LinkedList<FileMeta> files = new LinkedList<FileMeta>();
        // 返回值
        Map<String, Object> previewData = new HashMap<String, Object>();
        
        previewData.put("sta", "true");

        // 目录文件夹
        String dirPath = File.separatorChar + "template" + File.separatorChar + "upload";
        String uplaodPath = request.getSession().getServletContext().getRealPath(dirPath);
        // 定义当前时间，作为文件名称
        long time = System.currentTimeMillis() ;
        //2. get each file
        while(itr.hasNext()){

            //2.1 get next MultipartFile
            mpf = request.getFile(itr.next()); 
            System.out.println(mpf.getOriginalFilename() +" uploaded! "+files.size());
            
            /*String path = "D:/temp/files/" + File.separatorChar + time + "_" + mpf.getOriginalFilename();*/
            
            String path = uplaodPath + File.separatorChar + mpf.getOriginalFilename();

            //2.3 create new fileMeta
            FileMeta fileMeta = new FileMeta();
            fileMeta.setFileName(mpf.getOriginalFilename());
            fileMeta.setFileSize(mpf.getSize()/1024+" Kb");
            fileMeta.setFileType(mpf.getContentType());

            try {
                fileMeta.setBytes(mpf.getBytes());
                
                FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(path));
                
                // 设置图片预览地址
                fileMeta.setPreviewSrc(dirPath+File.separatorChar + mpf.getOriginalFilename());
           } catch (IOException e) {
               e.printStackTrace();
               // 设置图片上传失败
               previewData.put("sta", "false");
           }
            files.add(fileMeta);
            /*// 设置图片预览路径
            previewSrcList.add(path);*/
        }
        
       /* previewData.put("previewData", previewSrcList);*/
        previewData.put("files", files);
        
        
       return previewData;
    }
    
    /***************************************************
     * URL: /rest/controller/upload     , method = RequestMethod.POST
     * upload(): receives files
     * @param request : MultipartHttpServletRequest auto passed
     * @param response : HttpServletResponse auto passed
     * @return LinkedList<FileMeta> as json format   LinkedList<FileMeta>
     ****************************************************/
    @RequestMapping(value="/muliUploadAndPreview")
    @ResponseBody
    public Map<String, Object> muliUploadAndPreview(HttpServletRequest request, @RequestParam("files") CommonsMultipartFile[] file, HttpServletResponse response) {
        previewData.put("sta", "true");
        // 目录文件夹
        String dirPath = File.separatorChar + "template" + File.separatorChar + "upload";
        String uplaodPath = request.getSession().getServletContext().getRealPath(dirPath);
        // 定义当前时间，作为文件名称
        long time = System.currentTimeMillis() ;
        //2. get each file
       /* while(itr.hasNext()){*/
        if(file != null && file.length > 0) {
        	
        	for (CommonsMultipartFile cmf : file) {
        		
                System.out.println(cmf.getOriginalFilename() +" uploaded! "+files.size());
                
                
                String path = uplaodPath + File.separatorChar + cmf.getOriginalFilename();

                if(files.size() >= 10)
                    files.pop();

                //2.3 create new fileMeta
                fileMeta = new FileMeta();
                fileMeta.setFileName(cmf.getOriginalFilename());
                fileMeta.setFileSize(cmf.getSize()/1024+" Kb");
                fileMeta.setFileType(cmf.getContentType());

                try {
                    fileMeta.setBytes(cmf.getBytes());
                    
                    FileCopyUtils.copy(cmf.getBytes(), new FileOutputStream(path));
                    
                    // 设置图片预览地址
                    fileMeta.setPreviewSrc(dirPath+File.separatorChar + cmf.getOriginalFilename());
               } catch (IOException e) {
                   e.printStackTrace();
                   // 设置图片上传失败
                   previewData.put("sta", "false");
               }
                files.add(fileMeta);
        	}
        	
        	 previewData.put("files", files);
        }
       return previewData;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/uploadfile.json")
    @ResponseBody
    public Map jqueryUploadFile(@RequestParam("files") MultipartFile file){
        System.out.println(file.getOriginalFilename());
        Map map=new HashMap();
        map.put("name",file.getOriginalFilename());
        return map;
    }
    
    /***************************************************
     * URL: /rest/controller/get/{value}
     * get(): get file as an attachment
     * @param response : passed by the server
     * @param value : value from the URL
     * @return void
     ****************************************************/
    @RequestMapping(value = "/get/{value}", method = RequestMethod.GET)
     public void get(HttpServletResponse response, @PathVariable String value){
         FileMeta getFile = files.get(Integer.parseInt(value));
         try {      
                response.setContentType(getFile.getFileType());
                response.setHeader("Content-disposition", "attachment; filename=\""+getFile.getFileName()+"\"");
                FileCopyUtils.copy(getFile.getBytes(), response.getOutputStream());
         }catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
         }
     }

    @RequestMapping(value="/imageUpload")
    @ResponseBody
    public String imageUpload(@RequestParam(value="file",required=false) MultipartFile[] file,
                                     HttpServletRequest request)throws Exception{
        if (file.length == 0 || null == file) {
            return "error";
        }

        try {
            long time = System.currentTimeMillis() ;
            // 目录文件夹
            String dirPath = File.separatorChar + "template" + File.separatorChar + "upload";
            String uplaodPath = request.getSession().getServletContext().getRealPath(dirPath);

            String path = uplaodPath + File.separatorChar + time+".jpg";

            FileCopyUtils.copy(file[0].getBytes(), new FileOutputStream(path));
            return "success";
        } catch (Exception e) {
            return "error";
        }
    }
}
